Substrings¶

🎨 replace¶

In [1]:
'I applied to UofU'.replace('UofU', 'BYU')
Out[1]:
'I applied to BYU'

replace let's you replace a substring with another string.

In [2]:
'A normal looking phrase'.replace(' ', '-')
Out[2]:
'A-normal-looking-phrase'

By default, replace replaces all occurrences of the substring with its substitute.

In [11]:
'I like cats and cats'.replace('cats', 'dogs', 1)
Out[11]:
'I like dogs and cats'

You can provide a 3rd argument to replace to control how many substitutions can be made.

In [12]:
text = 'I like to eat pizza'
new_text = text.replace('pizza', 'soup')
print(text)
print(new_text)
I like to eat pizza
I like to eat soup

replace (and any other string function that returns a string) returns a new string.

It doesn't modify the input string.

🎨 in¶

In [13]:
'BYU' in 'I am a student at BYU.'
Out[13]:
True
In [14]:
'BYU' in 'This room is full of monkeys!'
Out[14]:
False

Use the in operator to determine whether a substring is present in a string.

🖌 Custom Character Classes¶

In [21]:
def is_vowel(letter: str) -> bool:
    return letter in 'AEIOUaeiou'

found = ''
for letter in 'The Aeneid is ancient Roman literature.':
    if is_vowel(letter):
        found += letter
print(found)
eAeeiiaieoaieaue
In [22]:
def is_vowel(letter):
    return letter.lower() in 'aeiou'

found = ''
for letter in 'The Aeneid is ancient Roman literature.':
    if is_vowel(letter):
        found += letter
print(found)
eAeeiiaieoaieaue

🧑🏽‍🎨 BYU Enthusiasts¶

Capitalize every letter in an input string that is part of BYU.

"be happy. yup." -> "Be happY. YUp."

In [32]:
def is_byu(letter: str) -> bool:
    return letter in 'byu'


def byu(text: str) -> str:
    """
    Capitalize every letter of `text` that is part of 'BYU'
    >>> byu('booky')
    'BookY'
    """
    new = ''
    for letter in text:
        if is_byu(letter):
            new += letter.upper()
        else:
            new += letter
    return new


def byu(text):
    for letter in 'byu':
        text = text.replace(letter, letter.upper())
    return text
In [28]:
def byu(text):
    """Capitalize every letter of `text` that is part of 'BYU'"""
In [ ]:
def byu(text):
    """Capitalize every letter of `text` that is part of 'BYU'"""
    result = ''
    for c in text:
        if c in 'byu':
            result += c.upper()
        else:
            result += c
    return result
In [33]:
print(byu('write "byu" in all-caps. By byu!'))
write "BYU" in all-caps. BY BYU!
In [34]:
print(byu('Any student, boy or girl, young or old, can be a yodeler.'))
AnY stUdent, BoY or girl, YoUng or old, can Be a Yodeler.

🖌 Early-return¶

In [41]:
def is_bracket(letter):
    return letter in '{}[]<>'

def has_brackets(text):
    for letter in text:
        if is_bracket(letter):
            return True
    return False
In [42]:
has_brackets('Just some words')
Out[42]:
False
In [43]:
has_brackets('A Python list prints like this: [1, 2, 3, 4]')
Out[43]:
True

👨🏼‍🎨 Odd Numbers¶

Write a function that indicates whether a string has odd-numbered digits in it.

(i.e. it has a '1', '3', '5', '7', or '9' in it)

In [44]:
def has_odds(text: str):
    """Return True if the text has odd-numbered digits"""
    for symbol in text:
        if symbol in '13579':
            return True
    return False
In [ ]:
def has_odds(text):
    """Return True if the text has odd-numbered digits"""
In [ ]:
def is_odd_digit(letter):
    return letter in '13579'

def has_odds(text):
    """Return True if the text has odd-numbered digits"""
    for letter in text:
        if is_odd_digit(letter):
            return True
    return False
In [45]:
has_odds('I have 2 apples to share with 4 people.')
Out[45]:
False
In [46]:
has_odds('I have 2 apples, and there are 34 people, but I will eat them all!')
Out[46]:
True

👩🏼‍🎨 True Blue¶

Write a function that indicates whether a text has any of the following substrings in it:

  • BYU
  • blue
  • cougar
In [69]:
def is_true_blue(text):
    """Returns True if `text` contains any of: 'BYU', 'blue', or 'cougar'"""
    key_words = ['byu', 'blue', 'cougar']
    for key_word in key_words:
        if key_word in text.lower():
            return True
    return False
        
In [54]:
def is_true_blue(text):
    """Returns True if `text` contains any of: 'BYU', 'blue', or 'cougar'"""
In [ ]:
def is_true_blue(text):
    """Returns True if `text` contains any of: 'BYU', 'blue', or 'cougar'"""
    for word in ['BYU', 'blue', 'cougar']:
        if word in text:
            return True
    return False
In [70]:
is_true_blue('My friend goes to UVU')
Out[70]:
False
In [71]:
is_true_blue('I love BYU!')
Out[71]:
True
In [72]:
is_true_blue('The sky is blue'), is_true_blue('Blue skies, shining on me')
Out[72]:
(True, True)
In [73]:
is_true_blue('Don\'t touch the cougar')
Out[73]:
True

🎨 in and list¶

In [74]:
numbers = [1, 5, 9]
print(4 in numbers)
print(5 in numbers)
False
True
In [79]:
words = ['foo', 'bar', 'baz']
print('pizza' in words)
print('baz' in words)
False
True

👩🏻‍🎨 You already said that...¶

Write a program that queries a user for a list of fruits.

If the user says a fruit that has already been given, say "You already said that."

The program should ignore casing (uppercase vs lowercase).

Once 10 fruits have been given, print "Way to go!" and end the program.

fruits.py¶

Fruit: pear
Fruit: apple
Fruit: Pear
You already said that.
Fruit: kiwi
Fruit: BANANA
Fruit: pear
You already said that.
Fruit: APPLE
You already said that.
Fruit: Orange
Fruit: lemon
Fruit: lime
Fruit: cherry
Fruit: orange
You already said that.
Fruit: guava
Fruit: plum
Way to go!

Key Ideas¶

  • substrings
  • replace
  • in
  • Custom character classes using in
  • Early-return pattern
  • in and list